﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using SalePartial.Utility;
using System.Data;
using SalePartial.BLL;
using XunPan.Web.Globals;
using SalePartial.Model;
using Telerik.Web.UI;
using System.Drawing;

public partial class Trade_Events_event_detail : System.Web.UI.Page
{
   
    protected void Page_Load(object sender, System.EventArgs e)
    {
        
        
        if (!IsPostBack)
        {
            ////■■■■■テストため■■■■
            //UserBLL.StoreUserInfoToSession("j@j10.com");
            LoginUserType type = RoleControlManager.checkUserAuthority(User.Identity.Name);
            if (type == LoginUserType.FREE_PURCHASE
                || type == LoginUserType.CERT_PURCHASE || type == LoginUserType.CERT_SUP_PUR
                || type == LoginUserType.FREE_SUP_PUR)
            {

                if (HttpContext.Current.Session["InquiryID"] != null)
                {
                    string inquiryID = (string)HttpContext.Current.Session["InquiryID"];

                    ltrInquiryID.Text = inquiryID;
                     
                    //sdsQuoteList.SelectParameters("InquiryID").DefaultValue = "bfab11b4-b021-4347-824d-26b33c7b733a"
                    //sdsInquiryDetail.SelectParameters("InquiryID").DefaultValue = "bfab11b4-b021-4347-824d-26b33c7b733a"

                    sdsQuoteList.SelectParameters["InquiryID"].DefaultValue = inquiryID;
                    sdsInquiryDetail.SelectParameters["InquiryID"].DefaultValue = inquiryID;

                    string displaytext = rpbNavigator.FindItemByValue("All").Text;

                    for (int i = 0; i <= 10; i++)
                    {
                        displaytext = displaytext.Insert(displaytext.IndexOf(" "), "&nbsp;&nbsp;");
                    }
                    rpbNavigator.FindItemByValue("All").Text = displaytext;

                    displaytext = rpbNavigator.FindItemByValue("New").Text;
                    for (int i = 0; i <= 12; i++)
                    {
                        displaytext = displaytext.Insert(displaytext.IndexOf(" "), "&nbsp;&nbsp;");
                    }
                    rpbNavigator.FindItemByValue("New").Text = displaytext;

                    displaytext = rpbNavigator.FindItemByValue("Backup").Text;
                    for (int i = 0; i <= 10; i++)
                    {
                        displaytext = displaytext.Insert(displaytext.IndexOf(" "), "&nbsp;&nbsp;");
                    }
                    rpbNavigator.FindItemByValue("Backup").Text = displaytext;

                    displaytext = rpbNavigator.FindItemByValue("Assigned").Text;
                    for (int i = 0; i <= 6; i++)
                    {
                        displaytext = displaytext.Insert(displaytext.IndexOf(" "), "&nbsp;&nbsp;");
                    }
                    rpbNavigator.FindItemByValue("Assigned").Text = displaytext;

                    displaytext = rpbNavigator.FindItemByValue("Feedback").Text;
                    for (int i = 0; i <= 6; i++)
                    {
                        displaytext = displaytext.Insert(displaytext.IndexOf(" "), "&nbsp;&nbsp;");
                    }
                    rpbNavigator.FindItemByValue("Feedback").Text = displaytext;

                    InitializeEventRecordsOnMenuPanel();
                }
            }
            else
            {
                Response.Redirect(GlobalSetting.UrlHomePage, true);
            }
        }


    }

    private void InitializeEventRecordsOnMenuPanel()
    {
        //    '初始化所有数据记录数
        //string inquiryID = (string)HttpContext.Current.Items["InquiryID"];
        string inquiryID = ltrInquiryID.Text;

        XPQuote xpQuote = new XPQuote();
        DataSet ds = xpQuote.SelectByInquiryID(new Guid(inquiryID));
      
        DataView dv = ds.Tables[0].DefaultView;

        string displaytext = rpbNavigator.FindItemByValue("All").Text;

        displaytext = displaytext.Remove(displaytext.LastIndexOf(" ") + 1);
        displaytext = displaytext + dv.Count.ToString();
        rpbNavigator.FindItemByValue("All").Text = displaytext;


        dv.RowFilter = "SUBSTRING([QuoteStatus], 2, 2) = '10'";
        displaytext = rpbNavigator.FindItemByValue("New").Text;
        displaytext = displaytext.Remove(displaytext.LastIndexOf(" ") + 1);
        displaytext = displaytext + dv.Count.ToString();
        rpbNavigator.FindItemByValue("New").Text = displaytext;


        dv.RowFilter = "(SUBSTRING([QuoteStatus], 2, 1) = '1') AND (SUBSTRING([QuoteStatus], 5, 1) = '1')";
        displaytext = rpbNavigator.FindItemByValue("Backup").Text;
        displaytext = displaytext.Remove(displaytext.LastIndexOf(" ") + 1);
        displaytext = displaytext + dv.Count.ToString();
        rpbNavigator.FindItemByValue("Backup").Text = displaytext;

        dv.RowFilter = "(SUBSTRING([QuoteStatus], 2, 1) = '1') AND (SUBSTRING([QuoteStatus], 4, 1) = '1')";
        displaytext = rpbNavigator.FindItemByValue("Assigned").Text;
        displaytext = displaytext.Remove(displaytext.LastIndexOf(" ") + 1);
        displaytext = displaytext + dv.Count.ToString();
        rpbNavigator.FindItemByValue("Assigned").Text = displaytext;

        dv.RowFilter = "(SUBSTRING([QuoteStatus], 2, 1) = '1')  AND (SUBSTRING([QuoteStatus], 4, 1) = '1')AND (SUBSTRING([QuoteStatus], 6, 1) = '0')";
        displaytext = rpbNavigator.FindItemByValue("Feedback").Text;
        displaytext = displaytext.Remove(displaytext.LastIndexOf(" ") + 1);
        displaytext = displaytext + dv.Count.ToString();
        rpbNavigator.FindItemByValue("Feedback").Text = displaytext;
    }


    protected void radGridMainlist_ItemCommand(object source, Telerik.Web.UI.GridCommandEventArgs e)
    {
        switch (e.CommandName)
        {
            case "SetBackup":
                //候选报价状态设置

                if (radGridMainlist.SelectedIndexes.Count > 0)
                {

                    for (int i = 0; i <= radGridMainlist.SelectedIndexes.Count - 1; i++)
                    {
                        int index = Convert.ToInt32(radGridMainlist.SelectedIndexes[i]);

                        if (index >= 0)
                        {
                            string qid = e.Item.OwnerTableView.DataKeyValues[index]["QuoteID"].ToString();
                            if (GlobalUtility.IsValidGuid(qid))
                            {
                                try
                                {
                                    XPQuote xpQuote = new XPQuote();
                                    XPQuoteInfo quote = xpQuote.GetXPQuote(new Guid(qid));
                                    if (!quote.QuoteStatus.Substring(4, 1).Equals("1"))
                                    {
                                        quote.QuoteStatus = quote.QuoteStatus.Remove(4, 1);
                                        quote.QuoteStatus = quote.QuoteStatus.Insert(4, "1");
                                        xpQuote.Update(quote);
                                    }

                                }
                                catch (Exception ex)
                                {
                                    e.Canceled = true;

                                }
                            }

                        }
                    }
                    //FIXME:
                    //ReBindDataBySelect(rpbNavigator.SelectedItem);
                    radGridMainlist.DataBind();

                    InitializeEventRecordsOnMenuPanel();
                }
                break;
            case "CancelBackup":
                //候选报价状态设置

                if (radGridMainlist.SelectedIndexes.Count > 0)
                {

                    for (int i = 0; i <= radGridMainlist.SelectedIndexes.Count - 1; i++)
                    {
                        int index = Convert.ToInt32(radGridMainlist.SelectedIndexes[i]);

                        if (index >= 0)
                        {
                            string qid = e.Item.OwnerTableView.DataKeyValues[index]["QuoteID"].ToString();
                            if (GlobalUtility.IsValidGuid(qid))
                            {

                                try
                                {
                                    XPQuote xpQuote = new XPQuote();
                                    XPQuoteInfo quote = xpQuote.GetXPQuote(new Guid(qid));

                                    quote.QuoteStatus = quote.QuoteStatus.Remove(4, 1);
                                    quote.QuoteStatus = quote.QuoteStatus.Insert(4, "0");
                                    xpQuote.Update(quote);


                                }
                                catch (Exception ex)
                                {
                                    e.Canceled = true;

                                }
                            }

                        }
                    }
                    //FIXME:
                    //ReBindDataBySelect(rpbNavigator.SelectedItem);
                    radGridMainlist.Rebind();

                    InitializeEventRecordsOnMenuPanel();
                }
                break;
            case "SubmitFeedback":
                //提交反馈评价信息


                GridNestedViewItem nesteditem = (GridNestedViewItem)e.Item;
                GridDataItem dataitem = nesteditem.ParentItem;

                string qid2 = dataitem.OwnerTableView.DataKeyValues[dataitem.ItemIndex]["QuoteID"].ToString();
                string xpid = dataitem.OwnerTableView.DataKeyValues[dataitem.ItemIndex]["InquiryID"].ToString();

                XPRatingInfo rating = new XPRatingInfo();
                var _with1 = rating;

                _with1.RatingSubject = 3;
                _with1.RatingOwnerID = new Guid(xpid);
                _with1.RatingTargetID = new Guid(qid2);


                try
                {
                    Control dock = ((LinkButton)e.CommandSource).Parent;
                    Control con = default(Control);
                    con = dock.FindControl("rtbRateComment");
                    if (con != null)
                    {
                        _with1.RatingComment = ((RadTextBox)con).Text;
                    }

                    con = dock.FindControl("rRatingFromBuyer");

                    if (con != null)
                    {
                        _with1.RatingValue = Convert.ToInt16(((RadRating)con).Value);
                        if (_with1.RatingValue == -2 && string.IsNullOrEmpty(_with1.RatingComment))
                        {
                            con = dock.FindControl("phMessage");
                            Label msg = new Label();
                            msg.Text = "请填写补充说明";
                            msg.ForeColor = System.Drawing.Color.Red;

                            con.Controls.Add(msg);

                            e.Canceled = true;
                            break; // TODO: might not be correct. Was : Exit Select

                        }
                        else
                        {
                            XPRating xpRating = new XPRating();

                            xpRating.Insert(rating);
                            //设置反馈状态
                            XPQuote xpQuote = new XPQuote();
                            XPQuoteInfo quote = xpQuote.GetXPQuote(_with1.RatingTargetID);
                            quote.QuoteStatus = quote.QuoteStatus.Remove(6, 1);
                            quote.QuoteStatus = quote.QuoteStatus.Insert(6, "1");
                            xpQuote.Update(quote);

                            dataitem.OwnerTableView.Rebind();

                        }
                    }

                }
                catch (Exception ex)
                {
                    e.Canceled = true;
                    break; // TODO: might not be correct. Was : Exit Select
                }
                break;
            case "BlockVendor":
                break;
            //屏蔽供应商
            case "InquiryView":
                rdInquiryDetail.Visible = !rdInquiryDetail.Visible;

                break;
            case "Assign":

                string status = e.CommandArgument.ToString();

                GridDataItem gdataitem = null;
                gdataitem = (GridDataItem)e.Item;
                int result = 0;
                string InquiryStatus = gdataitem.GetDataKeyValue("InquiryStatus").ToString();
                if (EnableAssign(InquiryStatus,status))
                {
                    //Dim xpid As String = e.Item.OwnerTableView.Items(e.Item.ItemIndex)("InquiryID").ToString
                    //Dim qid As String = e.Item.OwnerTableView.Items(e.Item.ItemIndex)("QuoteID").ToString
                    
                    string xpid2 = gdataitem.GetDataKeyValue("InquiryID").ToString();
                    string qid = gdataitem.GetDataKeyValue("QuoteID").ToString();

                    result = ModerateBLL.AssignXP(xpid2, qid);
                    if (result > 0)
                    {
                        e.Item.OwnerTableView.Rebind();
                    }
                }
                break;
            case "ExpandCollapse":
                gdataitem = (GridDataItem)e.Item;
                string qid3 = gdataitem.GetDataKeyValue("QuoteID").ToString();

                 result = ModerateBLL.ReadQuote(qid3);
                if (result > 0)
                {
                    //e.Item.OwnerTableView.Rebind()
                }
                break;
            case "Feedback":
                //rdFeedback.Visible = true;
                lbtSubmitFeedback.CommandArgument = (string)e.CommandArgument;
                e.Item.Expanded = true;
                
                break;
            //e.ExecuteCommand(e.CommandName)
            //e.Canceled = False

        }

    }

    protected void radGridMainlist_ItemDataBound(object sender, GridItemEventArgs e)
    {
        if (e.Item is GridDataItem)
        {
            GridDataItem gdataitem = (GridDataItem)e.Item;

            string InquiryStatus = gdataitem.GetDataKeyValue("InquiryStatus").ToString();

            string qstatus = (((LinkButton)gdataitem["Assign"].FindControl("lbtAssign"))).CommandArgument.ToString();

            if (InquiryStatus.Substring(4, 1) == "1" && qstatus.Substring(3, 1) == "1")
            {
                gdataitem.BackColor = Color.Orange;
                gdataitem.ToolTip = "已授盘";
            }
        }
    }


    protected void rpbNavigator_ItemClick(object sender, Telerik.Web.UI.RadPanelBarEventArgs e)
    {
        if (e.Item.Items.Count > 0)
        {
            //主菜单框
            if (e.Item.Selected)
            {
                rpbNavigator.FindItemByValue("All").Selected = true;
                e.Item.Selected = false;
                radGridMainlist.Rebind();
            }
        }
        else
        {
            ReBindDataBySelect(e.Item);
        }
    }

    private void ReBindDataBySelect(RadPanelItem item)
    {
        //条目框
        if (item.Value != null && !string.IsNullOrEmpty(item.Value))
        {
            //这里将对数据集进行拣选
            switch (item.Value)
            {
                case "All":
                    sdsQuoteList.FilterExpression = "";

                    break;

                case "New":
                    sdsQuoteList.FilterExpression = "SUBSTRING([QuoteStatus], 2, 2) = '10'";
                    break;
                //sdsEventsList.SelectCommand = sdsEventsList.SelectCommand + " WHERE [VendorCompanyID] = '9fcb95d8-8de3-46df-8835-4010a90e8ad9'"

                case "Backup":
                    sdsQuoteList.FilterExpression = "(SUBSTRING([QuoteStatus], 2, 1) = '1') AND (SUBSTRING([QuoteStatus], 5, 1) = '1')";
                    break;
                //sdsEventsList.SelectCommand = sdsEventsList.SelectCommand + " WHERE [Importance] = 1"


                case "Assigned":
                    sdsQuoteList.FilterExpression = "(SUBSTRING([QuoteStatus], 2, 1) = '1') AND (SUBSTRING([QuoteStatus], 4, 1) = '1')";
                    break;
                //sdsEventsList.SelectCommand = sdsEventsList.SelectCommand + " WHERE [QuoteID] = '" & Guid.Empty.ToString & "'"

                case "Feedback":
                    sdsQuoteList.FilterExpression = "(SUBSTRING([QuoteStatus], 2, 1) = '1') AND (SUBSTRING([QuoteStatus], 6, 1) = '0')";
                    break;
                //sdsEventsList.SelectCommand = sdsEventsList.SelectCommand + " WHERE [QuoteID] = '" & Guid.Empty.ToString & "'"

                default:

                    return;

            }
            radGridMainlist.Rebind();

        }
    }

    protected bool EnableAssign(string InquiryStatus,string qstatus)
    {
        bool enable = false;
        try
        {
            //已授盘状态場合
            if (InquiryStatus.Substring(4, 1) == "1")
            {
                enable = false;

            }

            //检查已报价状态和未授盘状态
            else if (qstatus.Substring(3, 1) == "0")
            {
                enable = true;
            }
        }
        catch (Exception ex)
        {
            enable = false;
        }

        return enable;

    }
    protected bool EnableBuyerFeedback(string qstatus)
    {
        bool enable = false;
        try
        {
            //检查已授盘状态和未反馈状态
            if (qstatus.Substring(3, 1) == "1" && qstatus.Substring(6, 1) == "0")
            {
                enable = true;
            }
        }
        catch (Exception ex)
        {
            enable = false;
        }

        return enable;

    }
    protected string ParseQuoteStatus(string qstatus)
    {
        string display = "";
        try
        {
            //检查已读状态
            if (qstatus.Substring(2, 1) == "1")
            {
                display += "已查看/";
            }
            else
            {
                display += "未查看/";
            }
            //检查授盘状态
            if (qstatus.Substring(3, 1) == "1")
            {
                display += "已授盘/";
                //反馈状态
                if (qstatus.Substring(6, 1) == "1")
                {
                    display += "已评价/";
                }
                else
                {
                    display += "等待评价/";
                }
            }
            else
            { display += "未授盘/"; }

            if (display.EndsWith("/"))
            {
                display = display.TrimEnd("/".ToCharArray());
            }
        }
        catch (Exception ex)
        {
            display = "未知";
        }

        return display;

    }

    protected void lbtSubmitFeedback_Click(object sender, System.EventArgs e)
    {

        string xpid = lbtSubmitFeedback.CommandArgument;
        // string qid =  lbtFeedback.CommandArgument;


        XPRating xpRating = new XPRating();
        XPRatingInfo rating = new XPRatingInfo();
        var _with1 = rating;

        _with1.RatingSubject = 3;
        //采购商
        _with1.RatingOwnerID = new Guid(sdsQuoteDetail.SelectParameters["QuoteID"].DefaultValue);
        //供应商
        _with1.RatingTargetID = new Guid(xpid);
        _with1.RatingComment = rtbRateComment.Text;
        _with1.RatingValue = Convert.ToInt16(rRatingFromBuyer.Value);


        try
        {

            if (_with1.RatingValue == -1 && string.IsNullOrEmpty(_with1.RatingComment))
            {
                Label msg = new Label();
                msg.Text = "请填写补充说明";
                msg.ForeColor = System.Drawing.Color.Red;

                phMessage.Controls.Add(msg);

            }
            else
            {
                xpRating.Insert(rating);

                //设置反馈状态
                XPQuote xpQuote = new XPQuote();
                XPQuoteInfo quote = xpQuote.GetXPQuote(_with1.RatingOwnerID);
                quote.QuoteStatus = quote.QuoteStatus.Remove(6, 1);
                quote.QuoteStatus = quote.QuoteStatus.Insert(6, "1");
                xpQuote.Update(quote);
                pnlFeedback.Visible = false;
                sdsInquiryDetail.DataBind();
                radGridMainlist.Rebind();

                //发送系统邮件
                MembershipUser userInfo = Membership.GetUser(quote.UserID);
                if (userInfo != null)
                {
                    MailSendUtility.SyncSendMail(userInfo.Email, "零部件环球资源网--来自采购商的评价", "来自采购商的评价");
                }
                //消息
                XPNotificationInfo msg = new XPNotificationInfo();
                XPNotification xpNotifi = new XPNotification();

                msg.CreateUserID = new Guid(Session["UserID"].ToString());
                   // sdsInquiryDetail.SelectParameters["InquiryID"].DefaultValue);
                msg.Status = "0100000";
                msg.CreateDate = DateTime.Now;

                msg.RecipientUserID = quote.UserID;
               
                msg.Attachment = "";
                //msg.BodyText = "来自采购商的评价";
                msg.BodyText = "尊敬的供应商：</br>采购商"+
                  Session["UserName"].ToString() + "已经对询盘" + ltlPartName.Text+
                  "进行了反馈评价，具体内容为：</br>" + "反馈结果：" + _with1.RatingValue + "<br>" +
                "补充信息：" + _with1.RatingComment + "</br>如果您还没有提交对供应商的反馈，" +
                "请进入询盘填写提交。您的反馈评价非常重要，将有助于建立平台良好的信用体系。</br>"
                  + "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;谢谢!</br>"
                  + "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Fsafdsa网站客服";
                msg.SendDate = DateTime.Now;
       
                msg.Title = "零部件环球资源网--来自采购商的评价";
                msg.ContentType = 0;
                xpNotifi.Insert(msg);
            }
        }
        catch (Exception ex)
        {
        }
        Response.Redirect("PurchDetail.aspx");
    }


    protected void rRatingFromBuyer_Rate(object sender, EventArgs e)
    {
        UpdateBinaryRatingLabel();
    }

    private void UpdateBinaryRatingLabel()
    {
        //rRatingFromBuyer.Text = "Rating: " + rRatingFromBuyer.Value.ToString();

        if (rRatingFromBuyer.Value < 0)
        {
            rRatingFromBuyer.ForeColor = System.Drawing.Color.Red;
        }
        else
        {
            rRatingFromBuyer.ForeColor = System.Drawing.Color.Green;
        }
    }

}